<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input v-model="queryParams.keywords" placeholder="用户名/昵称/手机号" clearable @keyup.enter="handleQuery()" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="queryParams.gender" placeholder="全部" clearable @keyup.enter="handleQuery()"
            class="!w-[100px]">
            <el-option :value="1" label="男" />
            <el-option :value="2" label="女" />
            <el-option :value="0" label="保密" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="全部" clearable @keyup.enter="handleQuery()"
            class="!w-[100px]">
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['sys:worker:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button v-hasPerm="['sys:worker:delete']" type="danger" :disabled="removeIds.length === 0"
          @click="handleDelete()">
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row border
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="username" label="用户名" prop="username" min-width="150" align="center" />
        <el-table-column key="nickname" label="昵称" prop="nickname" min-width="150" align="center" />
        <el-table-column key="mobile" label="联系方式" prop="mobile" min-width="150" align="center" />
        <el-table-column label="性别" width="150" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.gender == 0" type="info">保密</el-tag>
            <el-tag v-if="scope.row.gender == 1" type="primary">男</el-tag>
            <el-tag v-if="scope.row.gender == 2" type="success">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="email" label="邮箱" prop="email" min-width="150" align="center" />
        <el-table-column label="状态" width="150" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 0" type="danger">禁用</el-tag>
            <el-tag v-if="scope.row.status == 1" type="primary">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column key="orgName" label="隶属机构" prop="orgName" width="150" align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button v-hasPerm="['sys:worker:edit']" type="primary" size="small" link
              @click="handleOpenDialog(scope.row.id)">
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button v-hasPerm="['sys:worker:delete']" type="danger" size="small" link
              @click="handleDelete(scope.row.id)">
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery()" />
    </el-card>

    <!-- 机构管理表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="handleCloseDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="用户名" />
        </el-form-item>

        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="formData.nickname" placeholder="昵称" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="formData.gender" class="!w-[100px]">
            <el-option :value="1" label="男" />
            <el-option :value="2" label="女" />
            <el-option :value="0" label="保密" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系方式" prop="mobile">
          <el-input v-model="formData.mobile" placeholder="联系方式" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="邮箱" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" class="!w-[100px]">
            <el-option :value="1" label="正常" />
            <el-option :value="0" label="禁用" />
          </el-select>
        </el-form-item>
        <el-form-item label="隶属机构" prop="orgName">
          <el-select v-model="formData.orgId">
            <el-option v-for="item in orgOptions" :value="item.orgId" :label="item.orgName">
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Worker",
  inheritAttrs: false,
});

import OrgAPI from '@/api/system/org.js';
import WorkerAPI, { WorkerForm, WorkerPageQuery, WorkerPageVO } from "@/api/system/worker.js";
import { useUserStore } from "@/store/modules/user";

const userInfo = useUserStore().userInfo
const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref<number[]>([]);
const total = ref(0);

const orgOptions = ref([])

const queryParams = reactive<WorkerPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 工人管理表格数据
const pageData = ref<WorkerPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 机构管理表单数据
const formData = reactive<WorkerForm>({});

// 机构管理表单校验规则
const rules = reactive({

});

/** 查询工人管理 */
function handleQuery() {
  loading.value = true;
  WorkerAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置工人管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 打开机构管理弹窗 */
async function handleOpenDialog(id?: number) {
  dialog.visible = true;

  //机构字典
  orgOptions.value = await OrgAPI.getOptions();
  if (id) {
    dialog.title = "修改工人信息";
    WorkerAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增工人信息";
    Object.assign(formData, {
      orgId: userInfo?.orgId,
      orgName: userInfo?.orgName
    });
  }
}

/** 提交机构管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        WorkerAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        WorkerAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭机构管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 删除机构管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      WorkerAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>

<style lang="scss" scoped></style>
